package com.vic.framework.helper;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Servlet 助手类
 * 
 * @author VIC
 *
 */
public final class ServletHelper {

	private static final Logger logger = LoggerFactory.getLogger(ServletHelper.class);

	private HttpServletRequest request;

	private HttpServletResponse response;

	/** 每个线程中一份ServletHelper */
	private static final ThreadLocal<ServletHelper> SERVLET_HELPER_HOLDER = new ThreadLocal<ServletHelper>();

	private ServletHelper(HttpServletRequest request, HttpServletResponse response) {
		super();
		this.request = request;
		this.response = response;
	}

	/** 初始化 */
	public static void init(HttpServletRequest request, HttpServletResponse response) {
		SERVLET_HELPER_HOLDER.set(new ServletHelper(request, response));
	}

	/**
	 * 销毁
	 */

	public static void destroy() {
		SERVLET_HELPER_HOLDER.remove();
	}

	/**
	 * 获取request
	 */
	public static HttpServletRequest getRequest() {
		return SERVLET_HELPER_HOLDER.get().request;
	}

	/**
	 * 获取response
	 */
	public static HttpServletResponse getResponse() {
		return SERVLET_HELPER_HOLDER.get().response;
	}

	/**
	 * 获取session
	 */
	public static HttpSession getSession() {
		return getRequest().getSession();
	}

	/**
	 * 获取ServletContext
	 */
	public static ServletContext getServletContext() {
		return getRequest().getServletContext();
	}

	/**
	 * 将属性放入request中
	 */
	public static void setRequestAttribute(String key, Object value) {
		getRequest().setAttribute(key, value);
	}

	/**
	 * 从request中获取
	 */
	public static Object getRequestAttribute(String key) {
		return getRequest().getAttribute(key);
	}
	
	/**
	 * 从request中移除属性
	 */
	public static void removeRequestAttribute(String key) {
		getRequest().removeAttribute(key);
	}

	/**
	 * 发送重定向响应
	 */
	public static void sendRedirect(String location) {
		try {
			getResponse().sendRedirect(getRequest().getContextPath() + location);
		} catch (IOException e) {
			logger.error("redirect failure", e);
		}
	}

	/**
	 * 将属性放入session中
	 */
	public static void setSessionAttribute(String key, Object value) {
		getSession().setAttribute(key, value);
	}
	

	/**
	 * 从session中获取
	 */
	public static Object getSessionAttribute(String key) {
		return getSession().getAttribute(key);
	}
	

	/**
	 * 从session中移除属性
	 */
	public static void removeSessionAttribute(String key) {
		getSession().removeAttribute(key);
	}
	
	
	/**
	 * 使session失效
	 */
	public static void invalidateSession(){
		getRequest().getSession().invalidate();
	}
	
}
